package com.zhongan.cloud.config.demo;

import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.Properties;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.stereotype.Component;

@Component
public class PropertyUtils {
    
    static class Test {
        public static void refresh() throws IllegalArgumentException, IllegalAccessException {
            ApplicationContext applicationContext = SpringUtils.getApplicationContext();
            DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
            String[] names = beanFactory.getSingletonNames();
            for (String name : names) {
                if (name.equals("helloController")) {
                    Object bean = ProxyTargetUtils.getTarget(beanFactory.getBean(name));
                    System.out.println(bean.getClass());
                    Field[] fields = bean.getClass().getDeclaredFields();
                    for (Field field : fields) {
                        field.setAccessible(true);
                        field.set(bean, "single");
                    }
                    System.out.println(bean);
                }
            }

            AnnotationConfigEmbeddedWebApplicationContext context = (AnnotationConfigEmbeddedWebApplicationContext) SpringUtils.getApplicationContext();
            ConfigurableEnvironment env = context.getEnvironment();
            MutablePropertySources mSources = env.getPropertySources();
            Iterator<PropertySource<?>> properties = mSources.iterator();
            /*while (properties.hasNext()) {
                PropertySource<?> property = properties.next();
                System.out.println(property.getName());
            }*/
            PropertySource<?> propertySource = mSources.get("class path resource [configServer.properties]");
            Properties pro = (Properties) propertySource.getSource();
            pro.put("config.name", "test");

            System.out.println(env.getProperty("config.name"));
            System.out.println(env.getSystemProperties());
        }
    }

    public static void refresh() throws IllegalArgumentException, IllegalAccessException {
        Test.refresh();
    }

}
